﻿using Domain.Material_Management;
using Domain.Production_Modules;
using Domain.QualityInspection_Modelling;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.QualityInspection_ModCom;
using ReturnValue;

namespace MES.Server.API.Application.Handler.QualityInspection_ModHandler
{
    public class UpdateQualityInspectionHandler : IRequestHandler<UpdateQualityInspectionCommand, ApiResult<QualityInspection>>
    {
        private readonly IRepository<QualityInspection> _qualityRepo;
        private readonly IRepository<MaterialGroupModel> _materialGroupRepo;
        private readonly IRepository<OrderModel> _orderRepo;

        public UpdateQualityInspectionHandler(
            IRepository<QualityInspection> qualityRepo,
            IRepository<MaterialGroupModel> materialGroupRepo,
            IRepository<OrderModel> orderRepo)
        {
            _qualityRepo = qualityRepo;
            _materialGroupRepo = materialGroupRepo;
            _orderRepo = orderRepo;
        }

        public async Task<ApiResult<QualityInspection>> Handle(UpdateQualityInspectionCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<QualityInspection>();

            // 1. 获取要更新的记录
            var inspection = await _qualityRepo.GetValue(request.Id);
            if (inspection == null)
                return result.Fail("质检记录不存在");

            // 2. 验证关联数据
            var orderExists = await _orderRepo.GetValue(request.ProductionOrderId) != null;
            if (!orderExists)
                return result.Fail("生产工单不存在");

            var groupExists = await _materialGroupRepo.GetValue(request.MaterialGroupId) != null;
            if (!groupExists)
                return result.Fail("物料群组不存在");

            // 3. 验证数量合理性
            if (request.InspectedQuantity <= 0)
                return result.Fail("检测数量必须大于0");

            if (request.QualifiedQuantity < 0 || request.QualifiedQuantity > request.InspectedQuantity)
                return result.Fail("合格数量必须在0到检测数量之间");

            // 4. 更新字段
            inspection.ProductionOrderId = request.ProductionOrderId;
            inspection.MaterialGroupId = request.MaterialGroupId;
            inspection.InspectedQuantity = request.InspectedQuantity;
            inspection.QualifiedQuantity = request.QualifiedQuantity;
            inspection.UnqualifiedQuantity = request.InspectedQuantity - request.QualifiedQuantity;
            inspection.Inspector = request.Inspector;
            inspection.InspectionTime = DateTime.Now;

            // 5. 保存更新
            var dbResult = await _qualityRepo.UpdateAsync(inspection);
            return dbResult > 0
                ? result.Success("质检记录更新成功", inspection)
                : result.Fail("质检记录更新失败");
        }
    }

}
